//app.js
import Api from 'api/api.js';
const api = new Api();
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null
  },
  OPEN_ID(){
    return wx.getStorageSync('OPEN_ID');
  },
  USER_ID(){
    // var user_id = wx.getStorageSync("USER_ID");
    return parseInt(this.getUserID()+"");
  },
  HOMENEEDFRESH:false,
  ORDER_TYPE:"5",
  BASE_ID:'0',
  qqmapkey: "BRDBZ-SVN36-ZILSW-EB2ZP-42W4S-HKFNS",
  APP_ID:"wxa6dfe474e971af8b",
  APP_SECRET :'fb7cb2151c536206053be7f737deaaeb',
  alert: function (message) {
    if (message){
      wx.showToast({
        title: message,
        icon: 'none',
        mask: true,
        duration: 1500
      });
    }
   
  },
  showToasts(message){
    if (message){
      wx.showToast({
        title: message,
        icon: 'success',
        mask: true,
        duration: 1500
      });
    }
  },
  isNumber(val) {
     var regPos = /^\d+(\.\d+)?$/; //非负浮点数
     var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; 
      if(regPos.test(val) || regNeg.test(val)) {
          return true;
        } else {
          return false;
         }
  },
  
  host: "https://www.topc10.com/discuz-api/",
 //host: "https://test.petbang2014.com/pet-api-test/",
// 选择并上传图片
chooseImageAndUpLoad(count){
  var _this = this;
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempPaths = res.tempFilePaths;
        var imageCount = tempPaths.length;
        var list = [];
        for (var i = 0;i < tempPaths.length;i++){
          var path = tempPaths[i];
          _this.upLoadImage(path).then(res=>{
            if (res){
              list.push(res);
              if (list.length == imageCount){
                resolve(list);
              }
            } else {
              resolve(null);
            }
          });     
        }
      },
    })
  });

  
},
upLoadImage(tempPath){
  var _this = this;
    wx.showLoading({
      title: '上传中...',
    })
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: this.host + this.upLoadImageUrl,
        filePath: tempPath,
        name: 'file',
        formData: {
          'user': 'test'
        },
        success: function (response) {
          wx.hideLoading();
          if (response.statusCode == 200){
            var string = response.data;
            var dict = JSON.parse(string);
            var url = dict.model.fileFullUrl;
            console.log(url);
            resolve(url);
          } else {
            resolve(null);
          }
        },
        fail: function (res) {
          wx.hideLoading();
        }
      })
    })

  
},
 getOpenIdTap: function() {
  var _this = this;
  return new Promise((resolve, reject) => {
    wx.login({
      success: function(data) {
        wx.request({
          //获取openid接口
          url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + _this.APP_ID + '&secret=' + _this.APP_SECRET + '&js_code=' + data.code + '&grant_type=authorization_code',
          data: {},
          method: 'GET',
          success: function(res) {
            wx.setStorageSync('OPEN_ID', res.data.openid);
            wx.setStorageSync('SESSION_KEY', res.data.session_key);
            wx.setStorageSync('UNIONID', res.data.unionid);
            resolve(res.data);
            console.log(res.data);
          }
        })
      }
    })
  });
  
},
getUserOpenIdData(){
  var _this = this;
  var map = {};
  var _this = this;
  api.authorizationCheck().then(res => {
    if (res.data.errorCode == 0) {
      var dict = res.data.model;
      wx.setStorageSync("headImage", dict.avatarUrl);
      wx.setStorageSync("nickName", dict.nickName);
      _this.getUnionIdData(dict);
    }
  }).catch(err => { });
},
getUserDataByOpenId(openId){
  var map = {};
  map.appId = this.APP_ID;
  map.openId = openId;
  return new Promise((resolve, reject) => {
    api.getRequestDataNoLoading(this.getUserDataByOpenIdUrl, map, false, "GET").then(res => {
      var userId = res.id + "";
      wx.setStorageSync("USER_ID", userId);
      resolve(userId);
    });
  });
},
getUnionIdAndOpenidData(){
  var _this = this;
  return new Promise((resolve, reject) => {
    wx.login({
      success: function(data) {
        var map = {};
        map.appId = _this.APP_ID;
        map.jsCode = data.code;
        api.getRequestDataNoLoading(_this.getOpenIdAndUnionId, map, false,"GET").then(res => {
          var unionid = res.unionid;
          var openId = res.openid;
          console.log("res=============",JSON.stringify(res));

          wx.setStorageSync('OPEN_ID', openId);
          wx.setStorageSync('UNIONID', unionid);
          _this.saveUserData().then(res => {
            resolve(res);
          });;
        });
      }
    })
  });

},
saveUserData(){
  var map = {};
  map.appId = this.APP_ID;
  // map.city = dict.city;
  // map.gender = dict.gender;
  map.headImgUrl = wx.getStorageSync('headImage');
  // map.mobile = dict.mobile;
  map.nickName = wx.getStorageSync('nickName');

  map.openId = wx.getStorageSync('OPEN_ID');
  map.unionId = wx.getStorageSync('UNIONID');
  var _this = this;
  return new Promise((resolve, reject) => {
    api.getRequestDataNoLoading(this.fanDataSaveUrl, map, false, "POST").then(res => {
      var openId = wx.getStorageSync("OPEN_ID");
      _this.getUserDataByOpenId(openId).then(res => {
        resolve(res);
      });

    });
  });

},
  getUserID(){
    var user_id = wx.getStorageSync('USER_ID');
    if (!user_id || user_id.length == 0){
      var openId = wx.getStorageSync('OPEN_ID');
      this.getUserDataByOpenId(openId).then(res=>{
        return res;
      });
    } else {
      return user_id;
    }
  },
  getNewUserData(){
    var _this = this;
    return new Promise((resolve, reject) => {
      wx.getUserInfo({
        success: function (res) {
          var dict = JSON.parse(res.rawData);
          wx.setStorageSync("headImage", dict.avatarUrl);
          wx.setStorageSync("nickName", dict.nickName);
          resolve(false);
        },
        fail: function (res) {
          resolve(true);
        }
      })
    });
  },
  getOpenIdData() {
    return new Promise((resolve, reject) => {
      var openId = wx.getStorageSync("OPEN_ID");
      var unionid = wx.getStorageSync("UNIONID");
      var userId = wx.getStorageSync("USER_ID");
      if (!openId || openId.length == 0 || !unionid || unionid.length == 0 || !userId || userId.length == 0) {
        this.getUnionIdAndOpenidData().then(res => {
          resolve(res);
        });
      } else {
        resolve(true);
      }
    });
 
  },



  // 接口名称
  fanDataSaveUrl: "api/fans/save",                                // 保存数据
  getOpenIdAndUnionId: "common/wechat/app/mini/openId/get",       // 获取openid
  postListUrl: "api/post/list",                                   // 帖子列表
  miePostListUrl:"api/post/myList",                               // 我的帖子列表
  postDetailtUrl: "api/post/detail",                              // 帖子详情
  postAgreeUrl:"api/postAgree/save",                              // 帖子点赞或者取消
  postSaveUrl: "api/post/save",                                   // 帖子保存
  postEditUrl:"api/post/update",                                  // 帖子修改
  postShareUrl:"api/post/share",                                  // 帖子分享
  postZhiDingUrl:"api/post/freshTop",                             // 帖子置顶 
  postDeleteUrl:"api/post/delete",                                // 帖子删除
  myFollowPostUrl:"api/post/myFollowList",                        // 我关注的帖子列表
  myShouChangPostUrl:"api/post/myCollectList",                    // 我收藏的帖子列表
  postShouChangUrl:"api/userCollect/save",                        // 帖子收藏
  userPostListUrl:"api/post/userPostList",                        // 用户帖子列表

  evalueSaveUrl:"api/comment/save",                               // 保存评论
  getUserDataByOpenIdUrl: "api/forum/user/findByOpenId",          // 获取用户信息接口    
  getUserDataByUserIdUrl:"api/forum/user/findByUserId",           // 获取用户信息通过userid
  commonAgreUrl: "api/comment/agree",                             // 帖子点赞或者取消 
  commonListUrl:"api/comment/list",                               // 评论列表接口

  userFansSaveUrl:"api/userFans/save",                            // 用户粉丝保存
  mineFollowUrl:"api/userFans/myFollowList",                      // 我关注的列表
  deleteUserFansUrl:"api/userFans/delete",                        // 用户粉丝删除
  deleteUserFansByUserId:"api/userFans/deleteByUserId",           // 用户粉丝删除
  mineFansUrl:"api/userFans/myFanList",                           // 我的粉丝列表
  isFollowUrl:"api/userFans/isFollow",                            // 是否关注某个人

  // 打赏
  mineGetDaShangUrl:"api/userReward/myReceiveList",               // 我收到的打赏列表
  mineGiveDaShangUrl:"api/userReward/myRewardList",               // 我打赏出去的列表
  rewardPayUrl:"api/userReward/save",                             // 打赏支付url
  payNofityUrl:"api/userReward/notify/order",                     // 支付回调
  mineDaShangDetailUrl:"api/userReward/detail",                   // 我的打赏明细

  zhongCaoListUrl:"api/userZhongcao/myReceiveZhongcaoList",        // 种草列表
  zhongCaoDetailUrl: "api/userZhongcao/detail",                    // 我的种草详情
  zhongCaoPayNotifyUrl: "api/userZhongcao/notify/order",           // 种草回调通知


  // 商品
  zhongCaoGoodsUrl:"api/product/zhongcaoList",                     // 种草商品列表
  bfGoodsUrl:"api/product/helpList",                               // 帮扶产品类表
  goodsDetailUrl:"api/product/detail",                             // 商品详情
  createOrderUrl:"api/forum/order/createOrder",                    // 创建订单
  buyGoodsListUrl:"api/product/buyRecord",                         // 购买记录
  payOrderUrl:"api/forum/order/pay",                               // 支付订单
  orderListUrl:"api/forum/order/list",                             // 订单列表
  orderDetailUrl:"api/forum/order/detail",                         // 订单详情
  orderFinishUrl:"api/forum/order/finish",                         // 订单完成

  // 商品评价
  goodsEvaluateUrl:"api/productComment/save",                      // 产品评论
  goodsEvaluateListUrl:"api/productComment/list",                  // 产品评论列表
  goodsEvaluateDeteleUrl:"api/productComment/delete",              // 删除产品评论

  userRenZhengUrl: "api/forum/user/auth",                          // 用户认证
  userDataUpdateUrl:"api/forum/user/update",                       // 用户资料修改


  // 文件上传
  upLoadImageUrl:"common/upload/upload",                           // 图片上传
  cityListUrl:"api/city/list",                                     // 城市列表

  jiDiListUrl:"api/bases/bangfuList",                               // 基地列表
  jdDiDetailUrl:"api/bases/detail",                                 // 基地详情
  // 我的帮扶
  mineBFJiDiListUrl:"api/userBangfu/myBangfuList",                  // 我的帮扶基地列表
  mineBFGoodsListUrl:"api/userBangfu/myBangfuOrderList",            // 我的帮扶产品列表

  // 购物车
  shopCartListUrl:"api/userCar/list",                                // 购物车列表
  deleteCartUrl:"api/userCar/delete",                                // 删除购物车
  saveCartUrl:"api/userCar/save",                                    // 购车车保存
  updateCartUrl: "api/userCar/update",                               // 购车车保存
  // 提现
  withdrawListUrl:"api/userWithdraw/list",                           // 提现列表
  withdrawUrl: "api/userWithdraw/withdraw",                          // 提现
  withdrawUpdateUrl: "api/userWithdraw/update",                      // 提现修改

  // 地址
  mineAdressList: "api/userAddress/list",                            // 地址列表
  addressSaveUrl:"api/userAddress/save",                             // 地址保存
  addressDeleteUrl:"api/userAddress/delete",                         // 删除获取地址
  addressEditUrl:"api/userAddress/update",                           // 地址修改

  juBaoSaveUrl:"api/report/save",                                    // 举报

  messageUserListUrl:"api/chat/listUser",                            // 消息用户列表
  messagListUrl:"api/chat/listChat",                                 // 消息列表
  messageSaveUrl:"api/chat/save",                                    // 消息保存
  messageAgreeAndCollectUrl:"api/message/agreeAndCollect",           // 帖子点赞收藏消息
  messageEvaluateUrl:"api/message/atAndComment",                     // 评论消息

  hostListUrl:"api/postTopic/list",                                  // 话题列表
  hostPostListUrl:"api/postTopic/postList",                          // 话题列表

  expressDetailUrl:"api/forum/order/express",                         // 快递详情
  voteSaveUrl:"api/postVoteUser/save",                                // 投票

  jiDiDongTaiListUrl:"api/assistUpdate/list",                         // 基地动态列表
  getQR:"common/wechat/app/getQr",                                    // 获取小程序码               
})